//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.filter;

import com.kun.framework.core.core.BeanFactory;
import com.kun.framework.core.util.SimpleKey;
import com.kun.framework.web.web.ContentResponseWrapper;
import com.kun.framework.web.web.controllers.wrapper.XssHttpServletRequestWrapper;
import com.kun.framework.web.web.handler.ExceptionHandler;
import com.kun.framework.web.web.sso.SsoService;
import com.kun.portal.webframe.exception.LoginFailException;
import com.kun.portal.webframe.po.FwParamConfigPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.service.FwLoginService;
import com.kun.portal.webframe.service.FwParamConfigService;
import com.kun.portal.webframe.util.LoginUtil;
import com.kun.portal.webframe.util.UserSessionUtil;
import com.kun.portal.webframe.vo.LoginConfigVo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.util.WebUtils;

public class DefaultFilter implements Filter {
    private static Logger LOG = LoggerFactory.getLogger(DefaultFilter.class);
    private String EXCEPT_PATH_REGEX = ".*/(Login|login|sso/|api/|open/).*";
    private boolean REST_AUTH = false;
    private String REST_AUTH_MODE = "DES";
    public static String ENCODING = "utf-8";
    private String DOCUMENT_PATTERN = ".*\\.(doc|docx|xsl|xslx|ppt|pptx|rar|zip|xml|txt|csv)";
    private String RESOURCE_PATTERN = ".*\\.(jpg|jpeg|bmp|gif|png|tng|css|js|swf|map|ico|ttf|woff|eot|svg|woff2)";
    private SsoService sso = new SsoService();
    private static final String STREAMING_ATTRIBUTE = DefaultFilter.class.getName() + ".STREAMING";
    private ExceptionHandler exceptionHandler;

    public DefaultFilter() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        if (session.getAttribute("mvcPath") != null) {
            session.setAttribute("mvcPath", session.getAttribute("mvcPath").toString().replaceAll("^/*", "/"));
        }

        String uri = request.getRequestURI();
        this.beforeFilter(request, response, session);
        FwUserPo user = null;
        LoginConfigVo loginConfigVo = this.getLoginConfigVo(request, session);
        HttpServletResponse responseWrapp = response;
        boolean isResource = uri.matches(this.RESOURCE_PATTERN);
        if (!isResource) {
            if (!this.isAsyncDispatch(request) && !(response instanceof ContentResponseWrapper)) {
                responseWrapp = new DefaultFilter.HttpStreamingAwareContentResponseWrapper(response, request);
            }

            this.doAjaxRequest(request, (HttpServletResponse)responseWrapp);
            user = this.getCuurUser(request, (HttpServletResponse)responseWrapp, session);
            if (user == null && !"all".equalsIgnoreCase(this.EXCEPT_PATH_REGEX) && !uri.matches(this.EXCEPT_PATH_REGEX)) {
                this.reGenerateSessionId(request);
                this.dealFirstPage(req, request, loginConfigVo, (HttpServletResponse)responseWrapp);
                return;
            }
        }

        boolean var17 = false;

        ContentResponseWrapper responseWrapper;
        label168: {
            try {
                var17 = true;
                if (loginConfigVo.getUseXssFilter().equals("true")) {
                    chain.doFilter(new XssHttpServletRequestWrapper(request), (ServletResponse)responseWrapp);
                    var17 = false;
                } else {
                    chain.doFilter(request, (ServletResponse)responseWrapp);
                    var17 = false;
                }
                break label168;
            } catch (Exception var18) {
                if (this.exceptionHandler == null) {
                    this.exceptionHandler = (ExceptionHandler)BeanFactory.getBean("exceptionHandler");
                }

                this.exceptionHandler.handler(request, (ServletResponse)responseWrapp, var18);
                var17 = false;
            } finally {
                if (var17) {
                    if (!isResource && !this.isAsyncStarted(request) && !isContentCachingDisabled(request)) {
                         responseWrapper = (ContentResponseWrapper)WebUtils.getNativeResponse((ServletResponse)responseWrapp, ContentResponseWrapper.class);
                        if (responseWrapper == null) {
                            LOG.error("{} ContentResponseWrapper not found", responseWrapper);
                        } else {
                            responseWrapper.copyBodyToResponse();
                        }
                    }

                }
            }

            if (!isResource && !this.isAsyncStarted(request) && !isContentCachingDisabled(request)) {
                responseWrapper = (ContentResponseWrapper)WebUtils.getNativeResponse((ServletResponse)responseWrapp, ContentResponseWrapper.class);
                if (responseWrapper == null) {
                    LOG.error("{} ContentResponseWrapper not found", responseWrapper);
                } else {
                    responseWrapper.copyBodyToResponse();
                }

                return;
            }

            return;
        }

        if (!isResource && !this.isAsyncStarted(request) && !isContentCachingDisabled(request)) {
            responseWrapper = (ContentResponseWrapper)WebUtils.getNativeResponse((ServletResponse)responseWrapp, ContentResponseWrapper.class);
            if (responseWrapper == null) {
                LOG.error("{} ContentResponseWrapper not found", responseWrapper);
            } else {
                responseWrapper.copyBodyToResponse();
            }
        }

    }

    private void dealFirstPage(ServletRequest req, HttpServletRequest request, LoginConfigVo loginConfigVo, HttpServletResponse responseWrapp) {
        String uri = request.getRequestURI();
        String firstPage = loginConfigVo.getFirstPage();
        String contextPath = request.getContextPath();
        String newUri = uri.replaceFirst(contextPath, "");
        String offset = "";
        String paras;
        if (newUri.length() > 1) {
            paras = "";
            if (req.getParameterMap().entrySet().size() > 0) {
                String paraKey;
                String paraVal;
                for(Iterator iter = req.getParameterMap().entrySet().iterator(); iter.hasNext(); paras = paras + paraKey + "=" + paraVal + "$") {
                    Entry<String, String[]> entry = (Entry)iter.next();
                    paraKey = (String)entry.getKey();
                    paraVal = ((String[])entry.getValue())[0];
                }

                paras = "?" + paras.substring(0, paras.length() - 1);
            }

            offset = (firstPage.indexOf("?") > 0 ? "&" : "?") + "redirect=" + newUri + paras;
        }

        offset = loginConfigVo.hasLoginPage() ? "" : offset;

        try {
            if (firstPage.startsWith("http://")) {
                responseWrapp.sendRedirect(firstPage + offset);
            } else {
                paras = contextPath + firstPage;
                responseWrapp.sendRedirect(paras + offset);
            }
        } catch (IOException var15) {
            var15.printStackTrace();
        }

    }

    private FwUserPo getCuurUser(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        FwUserPo user = null;

        try {
            user = UserSessionUtil.getCurrentUser(session);
            LoginUtil loginUtil = (LoginUtil)BeanFactory.getBean("loginUtil");
            if (!loginUtil.isCurrentAccountSession(user.getUserName(), session) || user.getUserName().equals("null")) {
                user = null;
                UserSessionUtil.clean(session);
            }
        } catch (LoginFailException var8) {
            session = this.reGenerateSessionId(request);
            String userName = this.sso.getUserIdFromCookie(request);
            if (userName != null && userName.length() > 0) {
                FwLoginService loginService = (FwLoginService)BeanFactory.getBean("loginService");
                user = loginService.findByUserNameEquals(userName,session);
                UserSessionUtil.setCurrentUser(session, user);
            }
        }

        return user;
    }

    private void beforeFilter(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String uri = request.getRequestURI();
        response.addHeader("Server", "SERVER");
        if (uri.matches(this.DOCUMENT_PATTERN)) {
            try {
                request.setCharacterEncoding(ENCODING);
                response.setContentType("application/octet-stream;charset=" + ENCODING);
            } catch (UnsupportedEncodingException var6) {
                ;
            }
        }

        if (session.getAttribute("REST_AUTH") == null) {
            session.setAttribute("REST_AUTH", this.REST_AUTH);
        }

        String contextPath;
        if (this.REST_AUTH && session.getAttribute("X-Auth-Token") == null) {
            contextPath = SimpleKey.genShortUuid() + SimpleKey.genShortUuid();
            session.setAttribute("X-Auth-Mode", this.REST_AUTH_MODE);
            session.setAttribute("X-Auth-Token", contextPath);
        }

        if (session.getAttribute("mvcPath") == null || session.getAttribute("springMvc") == null) {
            contextPath = request.getContextPath();
            session.setAttribute("mvcPath", contextPath);
            session.setAttribute("springMvc", contextPath);
        }

    }

    private void doAjaxRequest(HttpServletRequest request, HttpServletResponse responseWrapp) {
        boolean isAjax = request.getHeader("Request-Type") != null && "ajax".equalsIgnoreCase(request.getHeader("Request-Type"));

        try {
            if (isAjax) {
                request.setCharacterEncoding("utf-8");
                responseWrapp.setContentType("application/json;charset=utf-8");
            } else {
                request.setCharacterEncoding(ENCODING);
                responseWrapp.setCharacterEncoding(ENCODING);
                responseWrapp.setHeader("Charset", ENCODING);
                responseWrapp.setContentType("text/html;charset=" + ENCODING);
            }
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        }

    }

    public void init(FilterConfig config) throws ServletException {
        String encoding1 = config.getInitParameter("encoding");
        if (encoding1 != null && encoding1.length() > 0) {
            ENCODING = encoding1;
        }

        String except = config.getInitParameter("except_path_regex");
        if (except != null && except.length() > 0) {
            this.EXCEPT_PATH_REGEX = except;
        }

        String restAuth = config.getInitParameter("rest-auth");
        if ("true".equalsIgnoreCase(restAuth)) {
            this.REST_AUTH = true;
        }

        String restAuthMode = config.getInitParameter("rest-auth-mode");
        if (restAuthMode != null && restAuthMode.length() > 0) {
            this.REST_AUTH_MODE = restAuthMode;
        }

    }

    public static void disableContentCaching(ServletRequest request) {
        if (request != null) {
            request.setAttribute(STREAMING_ATTRIBUTE, true);
        }

    }

    protected boolean isAsyncStarted(HttpServletRequest request) {
        return WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted();
    }

    protected boolean isAsyncDispatch(HttpServletRequest request) {
        return WebAsyncUtils.getAsyncManager(request).hasConcurrentResult();
    }

    private static boolean isContentCachingDisabled(HttpServletRequest request) {
        return request.getAttribute(STREAMING_ATTRIBUTE) != null;
    }

    private LoginConfigVo getLoginConfigVo(HttpServletRequest request, HttpSession session) {
        if (session.getAttribute("loginConfigVo") != null) {
            return (LoginConfigVo)session.getAttribute("loginConfigVo");
        } else {
            FwParamConfigService fwParamConfigService = (FwParamConfigService)BeanFactory.getBean("fwParamConfigService");
            List<FwParamConfigPo> list = fwParamConfigService.findByParamTypeEquals("LoginConfig");
            LoginConfigVo loginConfigVo = new LoginConfigVo();
            Map<String, String> poMap = new HashMap();
            Iterator var7 = list.iterator();

            while(var7.hasNext()) {
                FwParamConfigPo item = (FwParamConfigPo)var7.next();
                poMap.put(item.getParamCode(), item.getParamValue());
            }

            try {
                BeanUtils.populate(loginConfigVo, poMap);
            } catch (InvocationTargetException | IllegalAccessException var9) {
                LOG.error(var9.getMessage(), var9);
            }

            session.setAttribute("loginConfigVo", loginConfigVo);
            return loginConfigVo;
        }
    }

    private HttpSession reGenerateSessionId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Map<String, Object> tempMap = new HashMap();
        Enumeration sessionNames = session.getAttributeNames();

        while(sessionNames.hasMoreElements()) {
            String sessionName = (String)sessionNames.nextElement();
            tempMap.put(sessionName, session.getAttribute(sessionName));
        }

        session.invalidate();
        session = request.getSession();
        Iterator var7 = tempMap.entrySet().iterator();

        while(var7.hasNext()) {
            Entry<String, Object> entry = (Entry)var7.next();
            session.setAttribute((String)entry.getKey(), entry.getValue());
        }

        return session;
    }

    public void destroy() {
    }

    static class HttpStreamingAwareContentResponseWrapper extends ContentResponseWrapper {
        private final HttpServletRequest request;

        public HttpStreamingAwareContentResponseWrapper(HttpServletResponse response, HttpServletRequest request) {
            super(response);
            this.request = request;
        }

        public ServletOutputStream getOutputStream() throws IOException {
            return this.useRawResponse() ? this.getResponse().getOutputStream() : super.getOutputStream();
        }

        public PrintWriter getWriter() throws IOException {
            return this.useRawResponse() ? this.getResponse().getWriter() : super.getWriter();
        }

        private boolean useRawResponse() {
            return DefaultFilter.isContentCachingDisabled(this.request);
        }
    }
}
